<template>
  <view class="resume-attach-container">
    <!-- 已上传简历展示区域 -->
    <view class="resume-item" v-for="(item, index) in resumeList" :key="item.id">
      <view class="resume-info">
        <image src="/static/jianli.png" class="file-icon"></image>
        <view class="resume-detail">
          <text class="file-name">{{ item.name }}</text>
          <text class="upload-time">324.6KB 更新于2023-03-15 15:30</text>
        </view>
      </view>
      <view class="delete-btn" @click="showActionSheet(item, index)">
        <view class="more-dots">
          <text class="dot"></text>
          <text class="dot"></text>
          <text class="dot"></text>
        </view>
      </view>
    </view>

    <!-- 预览简历的模态框 -->
    <u-modal
      v-model="dialogVisible"
      title="在线预览附件简历"
      :show-cancel-button="false"
      @close="handleClose"
    >
      <view class="modal-content">
        <iframe id="resume-iframe" :src="pdfUrl" style="width: 100%; height: 100vh"></iframe>
      </view>
    </u-modal>

    <!-- 提示信息 -->
    <view class="tip-container">
      <view class="exclamation-circle"></view>
      <text class="tip-text">最多支持上传3个文件,仅支持上传PDF格式的附件简历</text>
    </view>
    <!-- 上传按钮 -->
    <button class="upload-btn" @click="chooseResume">上传附件简历</button>
  </view>
</template>

<script>
import { getAttachment, delAttachment } from "@/api/attachmentResume.js";

export default {
  data() {
    return {
      resumeList: [],
      pageNum: 1,
      pageSize: 3,
      total: 0,
      dialogVisible: false,
      pdfUrl: "", // 预览的 PDF URL
      currentResume: null, // 当前操作的简历
    };
  },
  methods: {
    showActionSheet(item, index) {
      this.currentResume = { item, index }; // 保存当前操作的简历信息
      uni.showActionSheet({
        itemList: ["预览", "下载", "删除"],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.previewResume();
          } else if (res.tapIndex === 1) {
            this.downloadResume();
          } else if (res.tapIndex === 2) {
            this.deleteResume();
          }
        },
        fail: (err) => {
          console.log("取消操作");
        },
      });
    },
    async querAttachmentResume() {
      const res = await getAttachment(this.pageNum, this.pageSize);
      if (res.code === 200) {
        this.resumeList = res.data.list;
        this.total = res.data.list.length;
      }
    },
    // 预览简历
    async previewResume() {
      if (!this.currentResume || !this.currentResume.item || !this.currentResume.item.resumeUrl) {
        uni.showToast({
          title: '简历地址不存在',
          icon: 'none'
        });
        return;
      }
    
      const resumeUrl = this.currentResume.item.resumeUrl;
      
      try {
        // 显示加载状态
        uni.showLoading({
          title: '正在加载简历...',
          mask: true
        });
    
        // 检查文件类型
        const fileExtension = this.getFileExtension(resumeUrl);
        const supportedTypes = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'];
    
        if (!supportedTypes.includes(fileExtension.toLowerCase())) {
          uni.hideLoading();
          uni.showToast({
            title: '不支持的文件格式',
            icon: 'none'
          });
          return;
        }
    
        // 下载文件
        const downloadRes = await this.downloadFile(resumeUrl);
        
        if (downloadRes.statusCode === 200) {
          // 打开文档
          const openRes = await this.openDocument(downloadRes.tempFilePath, fileExtension);
          
          if (openRes.errMsg === 'openDocument:ok') {
            console.log('简历预览成功');
          } else {
            uni.showToast({
              title: '打开简历失败',
              icon: 'none'
            });
          }
        } else {
          uni.showToast({
            title: '下载简历失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('预览简历异常:', error);
        uni.showToast({
          title: '预览简历失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    
    // 获取文件扩展名
    getFileExtension(url) {
      if (!url) return '';
      const urlParts = url.split('?')[0];
      const fileName = urlParts.split('/').pop();
      return fileName.split('.').pop().toLowerCase();
    },
    
    // 下载文件
    downloadFile(url) {
      return new Promise((resolve, reject) => {
        uni.downloadFile({
          url: url,
          success: resolve,
          fail: reject
        });
      });
    },
    
    // 打开文档
    openDocument(filePath, fileType) {
      return new Promise((resolve, reject) => {
        uni.openDocument({
          filePath: filePath,
          fileType: fileType,
          success: resolve,
          fail: reject
        });
      });
    },
    
    // 下载简历
    downloadResume() {
      if (this.currentResume) {
        const url = this.currentResume.item.resumeUrl;
        //uniapp的原生下载方法
        uni.downloadFile({
          url: url,
          success: (res) => {
            if (res.statusCode === 200) {
              const filePath = res.tempFilePath;
              uni.saveFile({
                tempFilePath: filePath,
                success: (saveRes) => {
                  const savedFilePath = saveRes.savedFilePath;
                  uni.openDocument({
                    filePath: savedFilePath,
                    fileType: 'pdf',
                    success: () => {
                      console.log('文件打开成功');
                    },
                    fail: (err) => {
                      console.error('文件打开失败', err);
                    }
                  });
                },
                fail: (err) => {
                  console.error('文件保存失败', err);
                }
              });
            } else {
              console.error('文件下载失败', res);
            }
          },
          fail: (err) => {
            console.error('文件下载失败', err);
          }
        });
      }
    },
    async deleteResume() {
      if (this.currentResume) {
        const res = await delAttachment(this.currentResume.item.id);
        if (res.code === 200) {
          this.resumeList.splice(this.currentResume.index, 1);
        }
      }
    },
    
    // 选择文件
    chooseResume() {
      // 检查当前已上传的文件数量
      if (this.resumeList.length >= 3) {
        uni.showToast({
          title: '最多支持上传3个文件',
          icon: 'none',
          duration: 2000,
        });
        return; // 阻止继续上传
      }
    
      uni.chooseFile({
        count: 1, // 允许选择的文件数量
        type: 'file', // 选择文件类型
        success: (res) => {
          const tempFilePath = res.tempFiles[0].path; // 获取临时文件路径
          const fileName = res.tempFiles[0].name; // 获取文件名
          console.log("选择的文件路径:", tempFilePath);
          console.log("选择的文件名:", fileName);
    
          // 调用上传方法
          this.uploadResume(tempFilePath, fileName);
        },
        fail: (err) => {
          console.error('选择文件失败', err);
        }
      });
    },
    
    // 上传文件
    uploadResume(tempFilePath, fileName) {
      const uploadTask = uni.uploadFile({
        url: 'http://81.71.154.186:8088/api/files/uploadFile', 
        filePath: tempFilePath, // 临时文件路径
        name: 'file', // 后端接收文件的字段名
        formData: {
          'user': 'test' // 其他表单数据
        },
        success: (uploadRes) => {
          console.log("上传结果:", uploadRes);
          if (uploadRes.statusCode === 200) {
            const data = JSON.parse(uploadRes.data);
            if (data.code === 200) {
              // 上传成功，更新文件列表
              this.resumeList.push({
                id: data.data.id,
                name: fileName,
                resumeUrl: data.data.url,
                uploadTime: new Date().toISOString()
              });
              uni.showToast({
                title: '上传成功',
                icon: 'success',
                duration: 2000
              });
            } else {
              uni.showToast({
                title: '上传失败',
                icon: 'none',
                duration: 2000
              });
            }
          } else {
            uni.showToast({
              title: '上传失败',
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: (err) => {
          console.error('上传失败', err);
          uni.showToast({
            title: '上传失败',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
    
    handleClose() {
      this.dialogVisible = false;
    },
  },
  mounted() {
    this.querAttachmentResume(); // 初始加载
  },
};
</script>

<style scoped>
.resume-attach-container {
  padding: 16px;
  background-color: #fff;
  min-height: 100vh;
  box-sizing: border-box;
}

.resume-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 16px;
}

.resume-info {
  display: flex;
  align-items: center;
}

.file-icon {
  width: 60px;
  height: 60px;
  margin-right: 12px;
}

.resume-detail {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.file-name {
  font-size: 14px;
  color: #333;
}

.upload-time {
  font-size: 12px;
  color: #999;
}

.delete-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  margin-right: 2rpx;
}

.more-dots {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.dot {
  width: 6px;
  height: 6px;
  background-color: #999; /* 灰色点 */
  border-radius: 50%;
  margin: 0 2px; /* 水平间距 */
}

.tip-container {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.exclamation-circle {
  width: 14px;
  height: 14px;
  border-radius: 50%;
  border: 1px solid #b6ccd8;
  position: relative;
  margin-right: 8px;
  flex-shrink: 0; /* 防止图标被压缩 */
}

.exclamation-circle::after {
  content: "!";
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 12px;
  color: #b6ccd8;
  line-height: 1;
  margin-top: -1px; /* 微调垂直位置 */
}

.tip-text {
  font-size: 12px;
  color: #999;
  line-height: 16px; /* 与图标高度保持一致 */
}

.upload-btn {
  background-color: #b6ccd8;
  color: #fff;
  font-size: 14px;
  padding: 10rpx 2rpx;
  border-radius: 4px;
  width: 330px;
}

.modal-content {
  width: 100%;
  height: 100vh;
}
</style>